﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.IO;
//using System.Linq;
using System.Text;
using System.Threading;
//using System.Threading.Tasks;
using System.Windows.Forms;

namespace KeyEnter
{
    public partial class FormKeyEnter : Form
    {
        MouseHook hook = new MouseHook();
        KeyboardHookLib _keyboardHook;
        public FormKeyEnter()
        {
            InitializeComponent();
            InitKey();

            //安装勾子
            _keyboardHook = new KeyboardHookLib();
            _keyboardHook.InstallHook(this.OnKeyPress);
        }

        private void InitKey()
        {
            textBox10.Text = ConfigurationManager.AppSettings["startKey"];
            textBox11.Text= ConfigurationManager.AppSettings["endKey"];
            if(ConfigurationManager.AppSettings["starKey1"]=="1")
            {
                checkBox1.Checked = true;
            }
            textBox2.Text= ConfigurationManager.AppSettings["key1"];
            textBox12.Text= ConfigurationManager.AppSettings["time1"];
            if (ConfigurationManager.AppSettings["starKey2"] == "1")
            {
                checkBox2.Checked = true;
            }
            textBox3.Text = ConfigurationManager.AppSettings["key2"];
            textBox13.Text = ConfigurationManager.AppSettings["time2"];
            if (ConfigurationManager.AppSettings["starKey3"] == "1")
            {
                checkBox3.Checked = true;
            }
            textBox4.Text = ConfigurationManager.AppSettings["key3"];
            textBox14.Text = ConfigurationManager.AppSettings["time3"];
            if (ConfigurationManager.AppSettings["starKey4"] == "1")
            {
                checkBox4.Checked = true;
            }
            textBox5.Text = ConfigurationManager.AppSettings["key4"];
            textBox15.Text = ConfigurationManager.AppSettings["time4"];
            if (ConfigurationManager.AppSettings["starKey5"] == "1")
            {
                checkBox5.Checked = true;
            }
            textBox6.Text = ConfigurationManager.AppSettings["key5"];
            textBox16.Text = ConfigurationManager.AppSettings["time5"];
            if (ConfigurationManager.AppSettings["starKey6"] == "1")
            {
                checkBox6.Checked = true;
            }
            textBox7.Text = ConfigurationManager.AppSettings["key6"];
            textBox17.Text = ConfigurationManager.AppSettings["time6"];
            if (ConfigurationManager.AppSettings["starKey7"] == "1")
            {
                checkBox7.Checked = true;
            }
            textBox8.Text = ConfigurationManager.AppSettings["key7"];
            textBox18.Text = ConfigurationManager.AppSettings["time7"];
            if (ConfigurationManager.AppSettings["starKey8"] == "1")
            {
                checkBox8.Checked = true;
            }
            textBox1.Text = ConfigurationManager.AppSettings["key8"];
            textBox19.Text = ConfigurationManager.AppSettings["time8"];

            if (ConfigurationManager.AppSettings["fuQiChuanSong"] == "1")
            {
                checkBox9.Checked = true;
            }
            textBox20.Text= ConfigurationManager.AppSettings["zhiShen"]; 
        }

        /// <summary>
        /// 客户端键盘捕捉事件.
        /// </summary>
        /// <param name="hookStruct">由Hook程序发送的按键信息</param>
        /// <param name="handle">是否拦截</param>
        public void OnKeyPress(KeyboardHookLib.HookStruct hookStruct, out bool handle)
        {
            handle = false; //预设不拦截任何键
            
            Keys key = (Keys)hookStruct.vkCode;
            Console.WriteLine(key.ToString());
            if(key.ToString()== textBox10.Text.Trim() && textBox9.Text.Trim() != "")
            {
                ifdie = false;
                label2.Text = "卡键中";
                if(checkBox1.Checked)
                {
                    timer1.Interval = Convert.ToInt32(Convert.ToDouble(textBox12.Text) * 1000);
                    timer1.Start();
                }
                if (checkBox2.Checked)
                {
                    timer2.Interval = Convert.ToInt32(Convert.ToDouble(textBox13.Text) * 1000);
                    timer2.Start();
                }
                if (checkBox3.Checked)
                {
                    timer3.Interval = Convert.ToInt32(Convert.ToDouble(textBox14.Text) * 1000);
                    timer3.Start();
                }
                if (checkBox4.Checked)
                {
                    timer4.Interval = Convert.ToInt32(Convert.ToDouble(textBox15.Text) * 1000);
                    timer4.Start();
                }
                if (checkBox5.Checked)
                {
                    timer5.Interval = Convert.ToInt32(Convert.ToDouble(textBox16.Text) * 1000);
                    timer5.Start();
                }
                if (checkBox6.Checked)
                {
                    timer6.Interval = Convert.ToInt32(Convert.ToDouble(textBox17.Text) * 1000);
                    timer6.Start();
                }
                if (checkBox7.Checked)
                {
                    timer7.Interval = Convert.ToInt32(Convert.ToDouble(textBox18.Text) * 1000);
                    timer7.Start();
                }
                if (checkBox8.Checked)
                {
                    timer8.Interval = Convert.ToInt32(Convert.ToDouble(textBox19.Text) * 1000);
                    timer8.Start();
                }
                if (checkBox9.Checked)
                {
                    _keyboardHook.UninstallHook();
                    timer9.Start();
                }
            }

            else if (key.ToString() == textBox11.Text.Trim())
            {
                timer1.Stop();
                timer2.Stop();
                timer3.Stop();
                timer4.Stop();
                timer5.Stop();
                timer6.Stop();
                timer7.Stop();
                timer8.Stop();
                label2.Text = "已停止";
                timer9.Stop();

            }
        }

      

        private void TimerClick(string key)
        {
            string[] list = textBox9.Text.Split(',');
            for (int i = 0; i < list.Length; i++)
            {
                if (list[i] != "")
                {
                    string text = list[i];
                    Thread thread = new Thread(() =>
                    {
                        ClickKey(new IntPtr(Convert.ToInt32(text)), key);
                    });
                    thread.Start();
                }
            }
        }

        private void SaveKey()
        {
            Configuration config = System.Configuration.ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
            config.AppSettings.Settings["startKey"].Value = textBox10.Text;
            config.AppSettings.Settings["endKey"].Value = textBox11.Text;
            config.AppSettings.Settings["key1"].Value = textBox2.Text;
            config.AppSettings.Settings["time1"].Value = textBox12.Text;
            config.AppSettings.Settings["key2"].Value = textBox3.Text;
            config.AppSettings.Settings["time2"].Value = textBox13.Text;
            config.AppSettings.Settings["key3"].Value = textBox4.Text;
            config.AppSettings.Settings["time3"].Value = textBox14.Text;
            config.AppSettings.Settings["key4"].Value = textBox5.Text;
            config.AppSettings.Settings["time4"].Value = textBox15.Text;
            config.AppSettings.Settings["key5"].Value = textBox6.Text;
            config.AppSettings.Settings["time5"].Value = textBox16.Text;
            config.AppSettings.Settings["key6"].Value = textBox7.Text;
            config.AppSettings.Settings["time6"].Value = textBox17.Text;
            config.AppSettings.Settings["key7"].Value = textBox8.Text;
            config.AppSettings.Settings["time7"].Value = textBox18.Text;
            config.AppSettings.Settings["key8"].Value = textBox1.Text;
            config.AppSettings.Settings["time8"].Value = textBox19.Text;
            config.AppSettings.Settings["zhiShen"].Value = textBox20.Text.Trim();
            if (checkBox1.Checked)
            {
                config.AppSettings.Settings["starKey1"].Value = "1";
            }
            else
            {
                config.AppSettings.Settings["starKey1"].Value = "0";
            }
            if (checkBox2.Checked)
            {
                config.AppSettings.Settings["starKey2"].Value = "1";
            }
            else
            {
                config.AppSettings.Settings["starKey2"].Value = "0";
            }
            if (checkBox3.Checked)
            {
                config.AppSettings.Settings["starKey3"].Value = "1";
            }
            else
            {
                config.AppSettings.Settings["starKey3"].Value = "0";
            }
            if (checkBox4.Checked)
            {
                config.AppSettings.Settings["starKey4"].Value = "1";
            }
            else
            {
                config.AppSettings.Settings["starKey4"].Value = "0";
            }
            if (checkBox5.Checked)
            {
                config.AppSettings.Settings["starKey5"].Value = "1";
            }
            else
            {
                config.AppSettings.Settings["starKey5"].Value = "0";
            }
            if (checkBox6.Checked)
            {
                config.AppSettings.Settings["starKey6"].Value = "1";
            }
            else
            {
                config.AppSettings.Settings["starKey6"].Value = "0";
            }
            if (checkBox7.Checked)
            {
                config.AppSettings.Settings["starKey7"].Value = "1";
            }
            else
            {
                config.AppSettings.Settings["starKey7"].Value = "0";
            }
            if (checkBox8.Checked)
            {
                config.AppSettings.Settings["starKey8"].Value = "1";
            }
            else
            {
                config.AppSettings.Settings["starKey8"].Value = "0";
            }
            if (checkBox9.Checked)
            {
                config.AppSettings.Settings["fuQiChuanSong"].Value = "1";
            }
            else
            {
                config.AppSettings.Settings["fuQiChuanSong"].Value = "0";
            }

            config.Save(ConfigurationSaveMode.Modified);
        }

        private void Button2_Click(object sender, EventArgs e)
        {
            SaveKey();
            ifdie = false;
            label2.Text = "卡键中";
            if (checkBox1.Checked)
            {
                timer1.Interval = Convert.ToInt32(Convert.ToDouble(textBox12.Text) * 1000);
                timer1.Start();
            }
            if (checkBox2.Checked)
            {
                timer2.Interval = Convert.ToInt32(Convert.ToDouble(textBox13.Text) * 1000);
                timer2.Start();
            }
            if (checkBox3.Checked)
            {
                timer3.Interval = Convert.ToInt32(Convert.ToDouble(textBox14.Text) * 1000);
                timer3.Start();
            }
            if (checkBox4.Checked)
            {
                timer4.Interval = Convert.ToInt32(Convert.ToDouble(textBox15.Text) * 1000);
                timer4.Start();
            }
            if (checkBox5.Checked)
            {
                timer5.Interval = Convert.ToInt32(Convert.ToDouble(textBox16.Text) * 1000);
                timer5.Start();
            }
            if (checkBox6.Checked)
            {
                timer6.Interval = Convert.ToInt32(Convert.ToDouble(textBox17.Text) * 1000);
                timer6.Start();
            }
            if (checkBox7.Checked)
            {
                timer7.Interval = Convert.ToInt32(Convert.ToDouble(textBox18.Text) * 1000);
                timer7.Start();
            }
            if (checkBox8.Checked)
            {
                timer8.Interval = Convert.ToInt32(Convert.ToDouble(textBox19.Text) * 1000);
                timer8.Start();
            }
            if (checkBox9.Checked)
            {
                timer9.Start();
            }
        }

        private void ClickKey(IntPtr intPtr, string key)
        {
            
            int keyCode = (int)Convert.ToChar(key);
            //Win32.keybd_event((byte)Convert.ToChar(key), 0, 0, 0);
            Win32.SendMessage(intPtr, Win32.WM_KEYDOWN, keyCode, 0);
            Thread.Sleep(5);
            Win32.SendMessage(intPtr, Win32.WM_KEYUP, keyCode, 0);
            //Win32.keybd_event((byte)Convert.ToChar(key), 0, 0, 0);
        }


        private void ClickKeyByCode(IntPtr intPtr, int code)
        {

            //Win32.keybd_event((byte)Convert.ToChar(key), 0, 0, 0);
            Win32.SendMessage(intPtr, Win32.WM_KEYDOWN, code, 0);
            Thread.Sleep(5);
            Win32.SendMessage(intPtr, Win32.WM_KEYUP, code, 0);
            //Win32.keybd_event((byte)Convert.ToChar(key), 0, 0, 0);
        }

        private void Button3_Click(object sender, EventArgs e)
        {
            timer1.Stop();
            timer2.Stop();
            timer3.Stop();
            timer4.Stop();
            timer5.Stop();
            timer6.Stop();
            timer7.Stop();
            timer8.Stop();
            label2.Text = "已停止";
            timer9.Stop();
        }

 
        private void Button4_Click(object sender, EventArgs e)
        {
            hook = new MouseHook();
            hook.OnMouseActivity += Hook_OnMouseActivity;
            hook.Start();
        }

        private void Hook_OnMouseActivity(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                hook.Stop();
                Thread.Sleep(500);
                IntPtr hwnd = Win32.GetForegroundWindow();
                textBox9.Text += "," + hwnd.ToString();
            }
        }

        private void FormKeyEnter_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (_keyboardHook != null) _keyboardHook.UninstallHook();
        }

        private void NotifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.WindowState = FormWindowState.Normal;
            this.ShowInTaskbar = true;
        }


        protected override void WndProc(ref Message m)
        {
            if (m.Msg == 0x112)
            {
                if (m.WParam.ToInt64() == 0xF020)
                {
                    this.WindowState = FormWindowState.Minimized;
                    this.ShowInTaskbar = false;
                    return;
                }
            }
            base.WndProc(ref m);
        }

        bool ifdie = false;
        private void FuQiKaJian()
        {
            IntPtr hwnd = new IntPtr(Convert.ToInt32(textBox9.Text.Trim().Replace(",", "")));
            Image image = CaptureWindow(hwnd);
            Bitmap bitmap = new Bitmap(image);
            //bitmap.Save("C://图.jpg");
            //判断是否死亡
            Color color1 = bitmap.GetPixel(531, 271); //224,196,160
            Color color2 = bitmap.GetPixel(528, 286);//32,196,248
            //判断是否收到传送
            Color color3= bitmap.GetPixel(387, 479);//0,72,192
            Color color4 = bitmap.GetPixel(396, 467);//216,136,32
            WriteLog($"color1={color1.R.ToString()},{color1.G.ToString()},{color1.B.ToString()}");
            WriteLog($"color2={color2.R.ToString()},{color2.G.ToString()},{color2.B.ToString()}");
            WriteLog($"color3={color3.R.ToString()},{color3.G.ToString()},{color3.B.ToString()}");
            WriteLog($"color4={color4.R.ToString()},{color4.G.ToString()},{color4.B.ToString()}");
            if ((color1.R == 224 && color1.G == 196 && color1.B == 160) && (color2.R == 32 && color2.G == 196 && color2.B == 248))
            {
                //战斗失利
                WriteLog("检测到战斗失利");
                Color fuHuoButton = bitmap.GetPixel(351, 392); //56,152,200
                WriteLog($"fuHuoButton={fuHuoButton.R.ToString()},{fuHuoButton.G.ToString()},{fuHuoButton.B.ToString()}"); 
                if (fuHuoButton.R == 56 && fuHuoButton.G == 152 && fuHuoButton.B == 200)
                {
                    //原地复活
                    WriteLog("原地复活");

                    Win32.SendMessage(hwnd, 0x0201, 1, Convert.ToInt32(488 + (383 << 16)));
                    Thread.Sleep(5);
                    Win32.SendMessage(hwnd, 0x0202, 1, Convert.ToInt32(488 + (383 << 16)));
                }
                else
                {
                    //复活
                    WriteLog("普通复活");

                    Win32.SendMessage(hwnd, 0x0201, 1, Convert.ToInt32(420 + (383 << 16)));
                    Thread.Sleep(5);
                    Win32.SendMessage(hwnd, 0x0202, 1, Convert.ToInt32(420 + (383 << 16)));
                    Thread.Sleep(500);
                    ifdie = true;
                }
            }
            else if ((color3.R == 0 && color3.G == 72 && color3.B == 192) && (color4.R == 216 && color4.G == 136 && color4.B == 32))
            {
                //收到传送
                //吃置身
                ClickKey(hwnd, textBox20.Text.Trim());
                Thread.Sleep(500);
                //传送
                Win32.SendMessage(hwnd, 0x0201, 1, Convert.ToInt32(389 + (499 << 16)));
                Thread.Sleep(5);
                Win32.SendMessage(hwnd, 0x0202, 1, Convert.ToInt32(389 + (499 << 16)));
                Thread.Sleep(500);
                //不知道为啥y要减30
                Win32.SendMessage(hwnd, 0x0201, 1, Convert.ToInt32(343 + (355 << 16)));
                Thread.Sleep(5);
                Win32.SendMessage(hwnd, 0x0202, 1, Convert.ToInt32(343 + (355 << 16)));

                //重置复活
                ifdie = false;
            }
        }

        public static void WriteLog(string strLog)
        {
            //string sFilePath = Application.StartupPath + "\\log\\" + DateTime.Now.ToString("yyyyMM");
            //string sFileName = DateTime.Now.ToString("dd") + ".log";
            //sFileName = sFilePath + "\\" + sFileName; //文件的绝对路径
            //if (!Directory.Exists(sFilePath))//验证路径是否存在
            //{
            //    Directory.CreateDirectory(sFilePath);
            //    //不存在则创建
            //}
            //FileStream fs;
            //StreamWriter sw;
            //if (File.Exists(sFileName))
            ////验证文件是否存在，有则追加，无则创建
            //{
            //    fs = new FileStream(sFileName, FileMode.Append, FileAccess.Write);
            //}
            //else
            //{
            //    fs = new FileStream(sFileName, FileMode.Create, FileAccess.Write);
            //}
            //sw = new StreamWriter(fs);
            //sw.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "   ---   " + strLog);
            //sw.Close();
            //fs.Close();
        }


        /// <summary>
        /// 指定窗口截图
        /// </summary>
        /// <param name="handle">窗口句柄. (在windows应用程序中, 从Handle属性获得)</param>
        /// <returns></returns>
        public Image CaptureWindow(IntPtr handle)
        {
            IntPtr hdcSrc = Win32.GetDC(handle);
            Win32.Rect windowRect;
            Win32.GetWindowRect(handle, out windowRect);
            int width = windowRect.Right - windowRect.Left;
            int height = windowRect.Bottom - windowRect.Top;
            IntPtr hdcDest = Win32.CreateCompatibleDC(hdcSrc);
            IntPtr hBitmap = Win32.CreateCompatibleBitmap(hdcSrc, width, height);
            IntPtr hOld = Win32.SelectObject(hdcDest, hBitmap);
            Win32.BitBlt(hdcDest, 0, 0, width, height, hdcSrc, 0, 0, Win32.SRCCOPY);
            Win32.SelectObject(hdcDest, hOld);
            Win32.DeleteDC(hdcDest);
            Win32.ReleaseDC(handle, hdcSrc);
            Image img = Image.FromHbitmap(hBitmap);
            Win32.DeleteObject(hBitmap);
            return img;
        }

        private void Timer9_Tick(object sender, EventArgs e)
        {
            FuQiKaJian();
        }

        private void Timer1_Tick(object sender, EventArgs e)
        {
            if (!ifdie)
            {
                TimerClick(textBox2.Text);
            }
        }

        private void Timer2_Tick(object sender, EventArgs e)
        {
            if (!ifdie)
            {
                TimerClick(textBox3.Text);
            }
        }

        private void Timer3_Tick(object sender, EventArgs e)
        {
            if (!ifdie)
            {
                TimerClick(textBox4.Text);
            }
        }

        private void Timer4_Tick(object sender, EventArgs e)
        {
            if (!ifdie)
            {
                TimerClick(textBox5.Text);
            }
        }

        private void Timer5_Tick(object sender, EventArgs e)
        {
            if (!ifdie)
            {
                TimerClick(textBox6.Text);
            }
        }

        private void Timer6_Tick(object sender, EventArgs e)
        {
            if (!ifdie)
            {
                TimerClick(textBox7.Text);
            }
        }

        private void Timer7_Tick(object sender, EventArgs e)
        {
            if (!ifdie)
            {
                TimerClick(textBox8.Text);
            }
        }

        private void Timer8_Tick(object sender, EventArgs e)
        {
            if (!ifdie)
            {
                TimerClick(textBox1.Text);
            }
        }
    }
}
